<?php

namespace app\admin\service;

use app\admin\model\BoxArticle;
use app\admin\model\BoxArticleComment;
use app\admin\model\BoxGame;
use app\admin\model\BoxMemberInfo;
use app\admin\model\BoxTaskConfig;
use app\qsapi\model\BoxMyTask;
use app\qsapi\model\Member;
use app\qsapi\service\BoxTaskService;
use think\Db;
use think\Exception;

class BoxArticleService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new BoxArticle();
    }

    public  function  getList(): array
    {
        $param=request()->param();
        $map=[];
        if(isset($param['id']) && !empty($param['id'])){
            $map[] = ['id', '=', $param['id']];
        }
        if(isset($param['status']) && $param['status'] !=''){
            $map[] = ['status', '=', $param['status']];
        }
        if (isset($param['began_time']) && !empty($param['began_time'])) {
            $map[] = ['create_time', '>=', strtotime($param['began_time'])];
        }
        if (isset($param['time'][0]) && !empty($param['time'][0])) {
            $map[] = ['create_time', '>=', strtotime($param['time'][0])];

        }
        if (isset($param['time'][1]) && !empty($param['time'][1])) {
            $map[] = ['create_time', '<=', strtotime($param['time'][1])];
        }

        if (isset($param['is_official'])) {
            $map[] = ['is_official', '=', $param['is_official']];
        }
        if (isset($param['post_platform']) && !empty($param['post_platform'])) {
            $map[] = ['post_platform', '=', $param['post_platform']];
        }


        $boxArticleList = (new BoxArticle())->where($map)->order('id desc');
        $count = $boxArticleList->count();
        $list =$boxArticleList->page(PAGE, PERPAGE)->select();

        $member_ids=array_column($list->toArray(),'create_user');

        $game_ids=array_column($list->toArray(),'game_id');
        $game=(new BoxGame())->field('id,game_name')->whereIn('id',$game_ids)->select();

        $member_infos=(new Member())->field('id,nickname,avatar')->whereIn('id',$member_ids)->select();
        $member_infos=array_column($member_infos?$member_infos->toArray():[],null,'id');
        $game_infos=array_column($game?$game->toArray():[],null,'id');
        foreach ($list as  $k =>&$item){
            $item['game']=isset($game_infos[$item['game_id']])?$game_infos[$item['game_id']]:[];
            $item['create_time']=date('Y-m-d H:i:s',$item['create_time']);
            $item['member_info']=isset($member_infos[$item['create_user']])?$member_infos[$item['create_user']]:[];
        }
        //返回结果
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
    }

    /**
     * Desc : 帖子审核,并完成发帖,发布积分
     * User : Steven
     * Date : 2024-08-27 15:49
     * @return array|mixed
     */
    public function edit()
    {
        $param = request()->param();
        if($param['data']['status'] == 1){
            Db::startTrans();
            try {
                $data = $param['data'] ?? [];
                $param['data']['release_time'] = time();
                unset($data['create_time']);
                $return = parent::edit($data);
                if($return['code'] == 0){
                    $postPlatform = $param['data']['post_platform'] ?? 0;
                    $member_id = $param['data']['member_id'] ?? 0;
                    switch ($postPlatform){
                        case 1: //1=IOS
                            $postPlatform = 3; //3=IOS
                            break;
                        case 2: //2=ANDROID
                            $postPlatform = 2;  //2=安卓
                            break;
                        case 3: //3=PC
                            $postPlatform = 6; //6=PC
                            break;
                    }
                    //找到发帖每日任务的任务ID(task_id)
                    $map = [
                        ['task_type','=',2],
                        ['status','=',1],
                        ['type_flag','=',4],
                        ['start_time','<=',date('Y-m-d H:i:s')],
                        ['end_time','>=',date('Y-m-d H:i:s')],
                        // ['device','=',$postPlatform]
                    ];
                    $task_id = BoxTaskConfig::where($map)->where(function ($query) use ($postPlatform) {
                        $query->where(Db::raw("FIND_IN_SET('1',device)"));
                        $query->whereOr(Db::raw("FIND_IN_SET('{$postPlatform}',device)"));
                    })->value('id');
                    $result['task_id'] = $task_id ?? 0;
                    $result['create_time'] = $param['data']['create_time'];
                    $result['type'] = 10;
                    $ctime = date('Y-m-d',strtotime($result['create_time']));
                    //查询发帖日的发帖数量
                    $count = (new BoxMyTask())->where(['member_id'=>$member_id,'task_id'=>$task_id])->whereBetween('over_time',[$ctime.' 00:00:00',$ctime.' 23:59:59'])->count();
                    if(!empty($task_id) && !empty($member_id) && $count == 0) (new BoxTaskService())->taskSuccess($member_id,$result);
                }
                Db::commit();
                return message('审核成功');
            }catch (Exception $e){
                Db::rollback();
                return message($e->getMessage(),0);
            }

        }
        unset($param['data']['create_time']);
        return parent::edit($param['data']);
    }


    //官方发帖
    public function add(){
        $param = request()->param();
        $param['is_official'] = 1;
        $param['create_user'] = $param['member_id'] ?? 0;
        if($param['is_time_release'] == 1){
            $param['release_time'] = isset($param['release_time']) ? strtotime($param['release_time']) : time();
        }else{
            $param['release_time'] = time();
        }
        if(!empty($param['id'])){
            unset($param['create_time']);
        }
        $param['status'] = 1;//审核通过
        $param['attachments'] = json_encode($param['attachments']);
        return parent::edit($param);
    }

    /**
     * Desc : 获取官方账号
     * User : you name
     * Date : 2023-12-25 19:59
     */
    public function account($param): array
    {
        if(isset($param['nickname']) &&!empty($param['nickname'])){
            $map[] = ['b.nickname','like','%'.trim($param['nickname']).'%'];
        }
        $map[] = ['b.mark','=',1];
        $map[] = ['a.role','=',1];
        $map[] = ['b.source','=',2];
        $map[] = ['b.status','=',1];
        $map[] = ['b.log_off','=',0];
        $list = (new BoxMemberInfo())->alias('a')
            ->field('b.nickname,b.id,a.member_id')
            ->leftJoin('cq_member b','a.member_id=b.id')
            ->where($map)
            ->order('b.id','desc')
            ->paginate()->toArray();
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list['data'],
            "count" => $list['total'],
        );
    }


    /**
     * 对富文本信息中的数据
     * 匹配出所有的 <img> 标签的 src属性
     * @param string $contentStr 富文本字符串
     * @return array
     *
     */
    public function getPatternMatchImages($contentStr = ""){
        $imgSrcArr = [];
        //首先将富文本字符串中的 img 标签进行匹配
        $pattern_imgTag = '/<img\b.*?(?:\>|\/>)/i';
        preg_match_all($pattern_imgTag,$contentStr,$matchIMG);
        if (isset($matchIMG[0])){
            foreach ($matchIMG[0] as $key => $imgTag){
                //进一步提取 img标签中的 src属性信息
                $pattern_src = '/\bsrc\b\s*=\s*[\'\"]?([^\'\"]*)[\'\"]?/i';
                preg_match_all($pattern_src,$imgTag,$matchSrc);
                if (isset($matchSrc[1])){
                    foreach ($matchSrc[1] as $src){
                        //将匹配到的src信息压入数组
                        $imgSrcArr[] = $src;
                    }
                }
            }
        }
        //$pattern= '/<img\b.+\bsrc\b\s*=\s*[\'\"]([^\'\"]*)[\'\"]/iU';
        return $imgSrcArr;
    }


    /**
     * Desc : 获取官方贴热度最大值
     * User : you name
     * Date : 2023-12-26 18:05
     * @return array
     */
    public function hotNum(): array
    {
        $res = (new BoxArticle())->where(['is_official'=>1])->max('hot_num');
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $res,
        );
    }

    /**
     * Desc : 获取官方贴的最大排序值
     * User : you name
     * Date : 2024-01-10 10:46
     * @return array
     */
    public function officialSort(): array
    {
        $res = (new BoxArticle())->where(['is_official'=>1])->max('is_official_sort');
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $res,
        );
    }


    /**
     * Desc : 获取帖子或评论信息
     * User : you name
     * Date : 2023-12-26 18:05
     * @return array
     */
    public function getArticleOrCommentInfo(): array
    {
        $param = request()->param();
        if($param['type'] == 1){  //type=1 帖子,type=2 评论
            $res = (new BoxArticle())->field('title,content')->where(['id'=>$param['target_id']])->find();
        }else{
            $res = (new BoxArticleComment())->field('content')->where(['id'=>$param['target_id']])->find();
        }
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $res ?? [],
        );
    }

}